package com.example.software.controller;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Time;
import java.time.LocalDateTime;
import java.util.*;

// import org.apache.shiro.authz.annotation.RequiresPermissions;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.example.software.constant.JwtClaimsConstant;
import com.example.software.context.BaseContext;
import com.example.software.dto.doctorDTO;
import com.example.software.dto.doctorLoginDTO;
import com.example.software.entity.AdminEntity;
import com.example.software.entity.RecodeEntity;
import com.example.software.entity.Result;
import com.example.software.properties.JwtProperties;
import com.example.software.service.RecodeService;
import com.example.software.service.UserService;
import com.example.software.service.WorkdayService;
import com.example.software.utils.*;

import com.example.software.vo.RecodeVO;
import com.example.software.vo.doctorVO;
import com.example.software.vo.loginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import com.example.software.entity.DoctorEntity;
import com.example.software.service.DoctorService;


/**
 * 医生表
 *
 * @author wxy
 * @email wxy9496099@163.com
 * @date 2024-10-28 10:54:37
 */
@RestController
@Slf4j
@Api(tags = "医生相关接口")
@RequestMapping("software/doctor")
public class DoctorController {
    @Autowired
    private DoctorService doctorService;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RecodeService recodeService;

    @Autowired
    private UserService userService;

    @Autowired
    private WorkdayService workdayService;


    //医生叫号，根据医生id进行查询已核销的挂号记录，并从小到大排序，并且更新状态为已叫号，并且更新就诊时间


    @PutMapping("/call")
    @ApiOperation(value = "确认就诊")

    public Result call(Long id){
//        Long DoctorId = BaseContext.getCurrentId();
//        List<RecodeEntity> recodeEntities = recodeService.getByDoctorId(DoctorId);
//        List<RecodeVO> list2 = new ArrayList<>();
//
//        for (RecodeEntity recodeEntity : recodeEntities) {
//
//            RecodeVO recodeVO = new RecodeVO();
//            BeanUtils.copyProperties(recodeEntity,recodeVO);
//
//            recodeVO.setDoctor(doctorService.getById(recodeEntity.getDoctorId()));
//            recodeVO.setUser(userService.getById(recodeEntity.getUserId()));
//            recodeVO.setWorkday(workdayService.getById(recodeEntity.getWorkdayId()));
//
//            list2.add(recodeVO);
//        }
//        log.info("医生叫号");

        RecodeEntity recodeEntity = new RecodeEntity();
        recodeEntity.setId(id);
        recodeEntity.setState(5);

        Date today = new Date();
        // 如果你需要格式化日期，可以使用SimpleDateFormat
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(today);

        Time timeNow = new Time(System.currentTimeMillis());

        //新增。还未更新jar包
        int hour = timeNow.getHours();
//        System.out.println(hour);
        if (hour < 12) {
            recodeEntity.setVisitNoon(0);//上午
        } else if (hour >= 12 && hour < 18) {
            recodeEntity.setVisitNoon(1);//下午
        } else if (hour >= 18 && hour < 24) {
            recodeEntity.setVisitNoon(2);//晚上
        }

        recodeEntity.setVisitDay(formattedDate);
        recodeEntity.setVisitTime(timeNow);

        recodeService.updateById(recodeEntity);



        return Result.success("确认就诊成功");
    }


    /**
     * 医生登录
     */
    @PostMapping("/login")
    @ApiOperation(value = "医生登录")
    public Result<loginVO> login(@RequestBody doctorLoginDTO doctorDTO){

        log.info("登录：{}", doctorDTO);

        DoctorEntity doctorEntity = doctorService.login(doctorDTO);
        Map<String, Object> claims = new HashMap<>();

        claims.put(JwtClaimsConstant.doctor_ID, doctorEntity.getId());
        log.info("医生登录");

//        if(doctorEntity.getAuth() == 0){
//            Long store_id = storeService.getByEmployeeId(employee.getId());   //新增v1
//            //登录成功后，生成jwt令牌
//            System.out.println("store_id2 "+store_id);
//            claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
//            claims.put("store_id", store_id);  //新增v1
//            log.info("员工登录");
//        }else{
//            //如果是管理员就不用保存他对应的店铺id了
//            //登录成功后，生成jwt令牌
//            claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
//            log.info("管理员登录");
//        }

        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        loginVO doctorVO = com.example.software.vo.loginVO.builder()
                .id(doctorEntity.getId())
                .username(doctorEntity.getUsername())
                .name(doctorEntity.getName())
                .token(token)
                .auth(doctorEntity.getAuth())
                .build();

        return  Result.success(doctorVO);
    }

    @GetMapping ("/parseAdmin")
    @CrossOrigin
    @ApiOperation("解析token获取当前用户信息")
    public Result<doctorVO> parseToken(String token){

        log.info("解析token获取当前用户信息：{}",token);
        Map<String, Object> claims = null;
        //解析token
        try {
            claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("登录失效，请重新登录");
        }

        if (claims == null) {
            return Result.error("登录失效，请重新登录");
        }

        //获取用户id
        Long userId = Long.valueOf(claims.get(JwtClaimsConstant.doctor_ID).toString());

        //根据用户id查询用户信息
        DoctorEntity doctorEntity = doctorService.getById(userId);
        doctorVO doctorVO = new doctorVO();
        BeanUtil.copyProperties(doctorEntity,doctorVO);
//        if(doctorEntity.getAuth() == 1){
//
//            return Result.success(employeeVO);
//        }else if(employee.getAuth() == 0){
//            Long store_id = storeService.getByEmployeeId(employee.getId());   //新增v1
//            Store store = storeService.getById(store_id);
//            StoreVO storeVO = new StoreVO();
//
//            BeanUtil.copyProperties(store,storeVO);
//            employeeVO.setStoreVO(storeVO);
//            return Result.success(employeeVO);
//        }

        return Result.success(doctorVO);

    }

    /**
     * 列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "医生信息列表查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = true),
            @ApiImplicitParam(name = "size", value = "每页数量",dataType = "int"),
            @ApiImplicitParam(name = "departmentId", value = "科室id,如果查全部可以不传或者传0",dataType = "Long"),
            @ApiImplicitParam(name = "name", value = "医生姓名，如果查全部可以不传或者传空")
    })
   // @RequiresPermissions("software:doctor:list")
    public Result<PageUtils> list(@RequestParam String page,
                                  @RequestParam String size,
                                  @RequestParam(required = false) Long departmentId,
                                  @RequestParam(required = false) String name){

        Map<String, Object> params = new HashMap<>();
        params.put("page",page);
        params.put("limit",size);
        if (departmentId != null && departmentId != 0) {
            params.put("departmentId", departmentId);
        }
        if (name != null && !name.isEmpty()) {
            params.put("name", name);
        }

        System.out.println("params" +params);
        System.out.println("当前用户id"+BaseContext.getCurrentId());

        PageUtils page2 = doctorService.queryPage(params);

        return Result.success(page2);
    }

    /**
     * 信息
     */
    @GetMapping("/info")
    @ApiOperation("获取当前用户信息")
    // @RequiresPermissions("software:admin:info")
    public Result<doctorVO> info(){

        BaseContext.getCurrentId();
        DoctorEntity doctorEntity = doctorService.getById(BaseContext.getCurrentId());
        doctorVO doctorVO = new doctorVO();
        BeanUtil.copyProperties(doctorEntity,doctorVO);

        return Result.success(doctorVO);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @ApiOperation(value = "根据id查询医生信息")
    // @RequiresPermissions("software:doctor:info")
    public Result<doctorVO> info(@PathVariable("id") Long id){


		DoctorEntity doctor = doctorService.getById(id);

        doctorVO doctorVO = new doctorVO();

        BeanUtils.copyProperties(doctor,doctorVO);

        return Result.success(doctorVO);
    }

    /**
     * 保存
     */
    @PostMapping
    @ApiOperation(value = "新增医生信息")
    // @RequiresPermissions("software:doctor:save")
    public R save(@RequestBody doctorDTO doctorDTO){


        DoctorEntity doctor = new DoctorEntity();

        //属性拷贝
        BeanUtils.copyProperties(doctorDTO, doctor);

        doctor.setPassword(DigestUtils.md5DigestAsHex(doctor.getPassword().getBytes()));

        try {
            doctorService.save(doctor);
        }catch ( Exception e){
            return R.error("用户名或编号已存在");
        }


        return R.ok();
    }

    /**
     * 修改
     */
    @PutMapping
    @ApiOperation(value = "修改医生信息")
    // @RequiresPermissions("software:doctor:update")
    public R update(@RequestBody doctorDTO doctorDTO){

        DoctorEntity doctor = new DoctorEntity();

        //属性拷贝
       // BeanUtil.copyProperties(doctorDTO, doctor, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));

        if (!doctorDTO.getPassword().isEmpty() && doctorDTO.getPassword() != null){
            doctor.setPassword(DigestUtils.md5DigestAsHex(doctorDTO.getPassword().getBytes()));
        }
        if (doctorDTO.getUsername() != null && !doctorDTO.getUsername().isEmpty()){
            doctor.setUsername(doctorDTO.getUsername());
        }
        if (doctorDTO.getAuth() != null && !doctorDTO.getAuth().isEmpty()){
            doctor.setAuth(doctorDTO.getAuth());
        }

        doctor.setStatus(doctorDTO.getStatus());

        if (doctorDTO.getId() != null && !(doctorDTO.getId() ==0)){
            doctor.setId(doctorDTO.getId());
        }
        if (doctorDTO.getName() != null && !doctorDTO.getName().isEmpty()){
            doctor.setName(doctorDTO.getName());
        }
        if (doctorDTO.getAccount() != null && !doctorDTO.getAccount().isEmpty()){
            doctor.setAccount(doctorDTO.getAccount());
        }
        if (doctorDTO.getGender() != null && !doctorDTO.getGender().isEmpty()){
            doctor.setGender(doctorDTO.getGender());
        }
        if (doctorDTO.getAge() != null && !(doctorDTO.getAge() ==0)){
            doctor.setAge(doctorDTO.getAge());
        }
        if (doctorDTO.getFee() != null && !(doctorDTO.getFee() ==0) ){
            doctor.setFee(doctorDTO.getFee());
        }
        if (doctorDTO.getCareer() != null && !doctorDTO.getCareer().isEmpty()){
            doctor.setCareer(doctorDTO.getCareer());
        }
        if (doctorDTO.getDescription() != null && !doctorDTO.getDescription().isEmpty()){
            doctor.setDescription(doctorDTO.getDescription());
        }
        if (doctorDTO.getPicPath() != null && !doctorDTO.getPicPath().isEmpty()){
            doctor.setPicPath(doctorDTO.getPicPath());
        }
        if (doctorDTO.getRoom() != null && !doctorDTO.getRoom().isEmpty()){
            doctor.setRoom(doctorDTO.getRoom());
        }
//        System.out.println(doctor);

        try {
            doctorService.updateById(doctor);
        }catch ( Exception e){
            return R.error("用户名或编号已存在");
        }


        return R.ok();
    }

    /**
     * 删除
     */
    @DeleteMapping
    @ApiOperation(value = "批量删除医生信息")
    // @RequiresPermissions("software:doctor:delete")
    public R delete(@RequestBody Long[] ids){
		doctorService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
